#include "blockQueue.hpp"
#include "Task.hpp"

void *Producer(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        // 模拟生产者生产数据
        int x = rand() % 10 + 1;
        int y = rand() % 10 + 1;
        char op = ops[rand() % ops.size()];
        Task t(x, y, op);
        usleep(10);

        bq->push(t);
        pthread_mutex_lock(&print_mutex);
        cout << "生产了一个任务" << t.getTask() << " thread id:" << pthread_self() << endl;
        pthread_mutex_unlock(&print_mutex);
        sleep(1);
    }
}
void *Comsumer(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        Task t = bq->pop();
        pthread_mutex_lock(&print_mutex);
        t.run();
        cout << "处理任务" << t.getResult() << " thread id:" << pthread_self() << endl;
        pthread_mutex_unlock(&print_mutex);
    }
}
int main()
{
    srand(time(nullptr));
    BlockQueue<Task> *bq = new BlockQueue<Task>();
    pthread_t pro[5], com[3];
    for(int i=0;i<5;++i)
        pthread_create(pro+i, nullptr, Comsumer, (void *)bq);
    for(int i=0;i<3;++i)
        pthread_create(com+i, nullptr, Producer, (void *)bq);

    for(int i=0;i<5;++i)
        pthread_join(pro[i], nullptr);
    for(int i=0;i<3;++i)
        pthread_join(com[i], nullptr);
    delete bq;
    return 0;
}